<?php
namespace app\pc\controller;
use service\CacheService;
use service\JsonService;
use service\SystemConfigService;
use service\UtilService;
use service\WxpayService;
use service\VodService;
use think\Cookie;
use think\Request;
use think\Session;
use think\Url;
use app\pc\model\user\User;
use app\pc\model\user\MemberShip;
use app\pc\model\tindex\Catehome as catehomemodel;
use app\pc\model\special\Special;
use app\pc\model\special\SpecialSource;
use app\pc\model\live\LiveStudio;
use app\pc\model\tiku\Tbindke;
use app\pc\model\special\Lecturer;
use app\pc\model\special\SpecialBuy;
use app\pc\model\tiku\Chapters;
use app\pc\model\special\SpecialTask;
use app\pc\model\live\LivePlayback;
use app\pc\model\store\StoreOrder;
use app\pc\model\special\SpecialContent;

class Ke extends AuthController
{

    /*
 * 白名单
 * */
    public static function WhiteList()
    {
        return [
            'getSpecial'
        ];
    }
    protected function _initialize()
    {
        parent::_initialize();
        $this->cateid=$cateid=$this->request->param('cateid');
        $this->isopen();
    }
     /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function index(){
        list($sort,$type) = UtilService::getMore([
            ['sort', 'score'],
            ['type', ''],
            ['cateid', $this->cateid],
        ], $this->request, true);
        $this->assign('type',$type);
        $this->assign('sort',$sort);
        return $this->fetch("ke/index/index");
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function getSpecial(){
        $where = UtilService::getMore([
            ['cateid', $this->cateid],
            ['sort', $this->request->param('sort')],
            ['type', $this->request->param('type')],
            ['page', 1],
            ['limit', 10],
        ]);
       
        $kedata=Tbindke::getlist($where);
        $totalpage=ceil($kedata["count"]/$where["limit"]);
        return JsonService::successful(array("data"=>$kedata["data"],"totalpage"=>$totalpage));
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function list(){
        $type=$this->request->param('type');
        $sort="score";
        if($this->request->param('sort')!=''){
            $sort=$this->request->param('sort');
        }
        $seotitle='';
        if( $type==5)$seotitle='专栏';
        if( $type==4)$seotitle='直播';
        if( $type==3)$seotitle='点播';
        if( $type==2)$seotitle='音频';
        if( $type==1)$seotitle='图文';
        $this->assign('seotitle',$seotitle.'课程');
        $this->assign('sort',$sort);
        $this->assign('type',$type);
        return $this->fetch("ke/list/index");
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function course($special_id){

        if (!$special_id) $this->failed('缺少参数,无法访问');
        $special = Special::getOneSpecial($this->uid, $special_id, 0);
        if ($special === false) $this->failed(Special::getErrorInfo('无法访问'), Url::build('pc/ke/index'));
        $item=is_string($special["special"]) ? json_decode($special["special"], true) : $specialinfo;;
        

        $type=$item["type"];
        $count=0;
        //目录
        if($type!=4 || $type!=5){
            $chapters = Chapters::getList(array("special_id"=>$special_id,"limit"=>99));
        }
        
     
        //专题
        if ($type == SPECIAL_COLUMN) {
            $cloumnSource = SpecialSource::getSpecialSource($special_id, false, 10, 1);
            foreach ($cloumnSource as $k => $v) {
                $cloumnTask = Special::get($v['source_id']);
                $cloumnTask = $cloumnTask ? $cloumnTask->toArray() : [];
                //获得专题下面的素材
                $specialTask = array();
               
                $task = SpecialTask::where('is_show',1)->where('id',$v['source_id'])->find();
                if ($task ? $task = $task->toArray() : false){
                    $task['special_id'] = $v['special_id'];
                    $task['pay_status'] = $v['pay_status'];
                    $taskSpecialIsPay = self::specialIsPay($special_id,$this->uid);
                    if (!$taskSpecialIsPay){//如果整个专题免费，那么里面素材都免非，否则就默认素材本身的状态
                        $task['pay_status'] = $taskSpecialIsPay;
                    }
                    $specialTask[] = $task;
                }
              
                if ($cloumnTask) {
                    $cloumnTask['children'] = $specialTask;
                    $cloumnTask['pay_status'] = $v['pay_status'];//付费,先默认素材本身的付费状态
                    $specialIsPay = self::specialIsPay($v['source_id'],$this->uid);
                    if (!$specialIsPay){//如果整个专题免费，那么里面素材都免非，否则就默认素材本身的状态
                        $cloumnTask['pay_status'] = $specialIsPay;
                    }
                    $cloumnTask['pay_status'] = $specialIsPay;
                    $cloumnTask['cloumn_special_id'] = $special_id;
                    if ($cloumnTask['is_show'] == 1) {
                        $list[] = $cloumnTask;
                    }
                }
            }


            array_multisort(array_column($list,'sort'),SORT_DESC,$list);
            $chapters["data"]=$list;
        }
      
  
        if ($type == SPECIAL_LIVE) {
            $liveInfo = LiveStudio::where('special_id', $item['id'])->find();
            if (!$liveInfo) return $this->failed('直播间尚未查到！', Url::build('index/index'));
            if ($liveInfo->is_del) return $this->failed('直播间已经删除！', Url::build('index/index'));
           
            if($liveInfo["start_play_time"]>time())$livestauts="还没有开始";
            if($liveInfo["start_play_time"]>time() && $liveInfo["stop_play_time"]<time())$livestauts="进入直播间";
            if($liveInfo["stop_play_time"]<time())$livestauts="已结束";
            $where['stream_name']=$liveInfo['stream_name'];
            $where['page']=1;
            $where['limit']=20;
            $where['start_time']=$liveInfo["start_play_time"];
            $where['end_time']=$liveInfo["stop_play_time"];
            $data= LivePlayback::getLivePlaybackList($where);

            $this->assign('livestauts', $livestauts);
            $this->assign('liveInfo', $liveInfo);
        }
 
        $special_money = Special::where('id', $special_id)->field('money, pay_type')->find();
        if (in_array($special_money['money'], [0, 0.00]) || in_array($special_money['pay_type'], [PAY_NO_MONEY, PAY_PASSWORD])) {
            $isPay = 1;
        }else{
            $isPay = (!$this->uid || $this->uid == 0) ? false : SpecialBuy::PaySpecial($special_id, $this->uid);
        }
        $user_level = !$this->uid ? 0 : User::getUserInfo($this->uid);
     
       $this->assign('is_member', isset($user_level['level']) ? $user_level['level'] : 0);
        $this->assign('chapters', $chapters);
        $this->assign('teacher', Lecturer::details($item["lecturer_id"]));
        $this->assign('special_id', $special_id);
        $this->assign('count', $count);
        $this->assign('item',$item);
        $this->assign('type',$type);
        return $this->fetch("ke/course/index");
    }
        /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function chapter($id = 0, $special_id = 0){
        if (!$id) {
            return $this->failed('缺少课程id,无法查看',Url::build('ke/index'));
        }
        $taskInfo = SpecialTask::defaultWhere()->where('id', $id)->find();
        $special = Special::PreWhere()->where('id', $special_id)->find();

        if (!$special) {
            return $this->failed('您查看得专题不存在',Url::build('ke/index'));
        }
        if (!$taskInfo) {
            return $this->failed('课程信息不存在无法观看',Url::build('ke/index'));
        }
        if ($taskInfo['is_show'] == 0) {
            return $this->failed('该课程已经下架',Url::build('ke/index'));
        }
        //$isPay = SpecialBuy::PaySpecial($special_id, $this->uid);
        $special_content = SpecialContent::where('special_id',$special_id)->value("content");
        $content = htmlspecialchars_decode($taskInfo->detail ? $taskInfo->detail : $special_content);
        //$user_level = !$this->uid ? 0 : User::getUserInfo($this->uid);
        $taskInfo->content =  $content;
        $isPay = self::specialIsPay($special_id,$this->uid);
        if (!$isPay){
            $special_source = SpecialSource::where(['special_id' => $special_id,'source_id' => $id, 'pay_status' => 0])->find();
            if (!$special_source) {
                return $this->failed('请购买课程在来观看',Url::build('ke/index',array('id'=>$special_id)));
            }else{
                $special_source = $special_source->toArray();
                $taskInfo = SpecialTask::defaultWhere()->order('sort DESC')->where('id', $special_source['source_id'])->find();
                if(!$taskInfo){
                    return $this->failed('您选择的素材不存在',Url::build('ke/index',array('id'=>$special_id)));
                }
                $taskInfo->content =  $content;
            }
        }

        $type=$special["type"];
        $count=0;
        //目录
        if($type!=4 || $type!=5){
            $chapters = Chapters::getList(array("special_id"=>$special_id,"limit"=>99));
        }
        
     
        //专题
        if ($type == SPECIAL_COLUMN) {
            $cloumnSource = SpecialSource::getSpecialSource($special_id, false, 10, 1);
            foreach ($cloumnSource as $k => $v) {
                $cloumnTask = Special::get($v['source_id']);
                $cloumnTask = $cloumnTask ? $cloumnTask->toArray() : [];
                //获得专题下面的素材
                $specialTask = array();
               
                $task = SpecialTask::where('is_show',1)->where('id',$v['source_id'])->find();
                if ($task ? $task = $task->toArray() : false){
                    $task['special_id'] = $v['special_id'];
                    $task['pay_status'] = $v['pay_status'];
                    $taskSpecialIsPay = self::specialIsPay($special_id,$this->uid);
                    if (!$taskSpecialIsPay){//如果整个专题免费，那么里面素材都免非，否则就默认素材本身的状态
                        $task['pay_status'] = $taskSpecialIsPay;
                    }
                    $specialTask[] = $task;
                }
              
                if ($cloumnTask) {
                    $cloumnTask['children'] = $specialTask;
                    $cloumnTask['pay_status'] = $v['pay_status'];//付费,先默认素材本身的付费状态
                    $specialIsPay = self::specialIsPay($v['source_id'],$this->uid);
                    if (!$specialIsPay){//如果整个专题免费，那么里面素材都免非，否则就默认素材本身的状态
                        $cloumnTask['pay_status'] = $specialIsPay;
                    }
                    $cloumnTask['pay_status'] = $specialIsPay;
                    $cloumnTask['cloumn_special_id'] = $special_id;
                    if ($cloumnTask['is_show'] == 1) {
                        $list[] = $cloumnTask;
                    }
                }
            }


            array_multisort(array_column($list,'sort'),SORT_DESC,$list);
            $chapters["data"]=$list;
        }
      
        //dump($taskInfo->toArray());
        //exit;
        $this->assign('taskInfo',  $taskInfo->toArray());
        $this->assign('is_member', isset($user_level['level']) ? $user_level['level'] : 0);
        $this->assign('special_id', (int)$special_id);
        $this->assign('chapter_id', (int)$id);
        $this->assign('chapters', $chapters);
        $this->assign('specialInfo', json_encode($special->toArray()));
        $this->assign('isPay', (int)$isPay);

        return $this->fetch("ke/chapter/vod");
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function live(){
        
        return $this->fetch("ke/chapter/live/index");
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public function pay($special_id){
        $ispay=$this->specialIsPay($special_id,$this->uid);

        if($ispay==0){
            return $this->fetch("ke/paysuccess");
        }
        $special = Special::PreWhere()->find($special_id);
        if (!$special) return JsonService::status('ORDER_ERROR', '购买的专题不存在');
        $order = StoreOrder::createSpecialOrder($special, 0, 2, $this->uid,'weixin', 0, 1);
        $orderId = $order['order_id'];
        $info = compact('orderId');
        $this->assign('order',$order);
        $this->assign('special',$special);
        $this->assign('orderId',$orderId);
        return $this->fetch("ke/pay");
    }
            /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
public function gopay($orderId){
    if ($orderId) {
        $orderInfo = StoreOrder::where('order_id', $orderId)->find();
        if (!$orderInfo || !isset($orderInfo['paid'])) return JsonService::status('pay_error', '支付订单不存在!');
        if ($orderInfo['paid']) return JsonService::status('pay_error', '支付已支付!');

        if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
            if (StoreOrder::jsPayPrice($orderId, $this->userInfo['uid']))
                return JsonService::status('success', '微信支付成功', $info);
            else
                return JsonService::status('pay_error', StoreOrder::getErrorInfo());
        }
        $payType=$this->request->param('payType');
 
        if($payType=="wxpay"){
            $wechat = SystemConfigService::more(['wechat_appid','wechat_appsecret','wechat_token']);
            $payment = SystemConfigService::more(['pay_weixin_mchid','pay_weixin_client_cert','pay_weixin_client_key','pay_weixin_key','pay_weixin_open']);
           
             $this->appid=isset($wechat['wechat_appid']) ? $wechat['wechat_appid']:'';
             $this->secret=isset($wechat['wechat_appsecret']) ? $wechat['wechat_appsecret']:'';
             $this->token=isset($wechat['wechat_token']) ? $wechat['wechat_token']:'';
             $this->mchid=$payment['pay_weixin_mchid'];
             $this->apiKey=$payment['pay_weixin_key'];

            $wxPay = new WxpayService($this->mchid,$this->appid,$this->apiKey);
            $outTradeNo = $orderInfo['id'];   
            $notifyUrl = "https://".$_SERVER['HTTP_HOST'].Url::build('Paysuccess/kepay_success',array("orderId"=>$orderId));   

            //付款成功后的回调地址(不要有问号)
            $payTime = time();      //付款时间
            $orderName="购买会员";
            $payAmount=$orderInfo['pay_price'];
            $wechat_result = $wxPay->createJsBizPackage($payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);//创建成功会微信返回的数据
            return JsonService::successful("ok",$wechat_result);
            //$this->assign('wechat_result',$wechat_result);
        }
        if($payType=="alipay"){
            $info['pay_price'] = $orderInfo['pay_price'];
            $info['orderName'] = '会员购买';
            $alipayurl=Url::build('alipay/index',array('info', base64_encode(json_encode($info))));

            header("Location: " .$alipayurl);
        }
    } else {
        return JsonService::fail(StoreOrder::getErrorInfo('订单生成失败!'));
    }
}
        /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
public function paystatus($orderId){
    if (is_string($orderId))
        $orderInfo = StoreOrder::where('order_id', $orderId)->find();
    else
        $orderInfo = $orderId;
    if (!$orderInfo || !isset($orderInfo['paid'])) JsonService::fail('支付订单不存在');
    if ($orderInfo['paid']) return JsonService::successful("ok",$orderInfo);
    JsonService::fail('fail');

}
   /**获取视频上传地址和凭证
     * @param string $videoId
     * @param int $type
     */
    public function get_video_playback_credentials($type=1,$videoId='')
    {
        $url=VodService::videoUploadAddressVoucher('',$type,$videoId);
        return JsonService::successful($url);
    }
        /**专题是否需要付费
     * @param $special_id
     * @return int
     * @throws \think\exception\DbException
     */
    public static function specialIsPay($special_id,$uid)
    {
        if (!$special_id) return false;
        $special = Special::get($special_id);
        if (!$special) return false;
        $specialIsPay = 1;//收费
        if(!$uid) return $specialIsPay;
        $uid = User::getActiveUid();
        $isMember = User::getUserInfo($uid);
        $isPay = SpecialBuy::PaySpecial($special['id'], $uid);

        if ($special['pay_type'] == 0) {//专栏里面整个专题免费
            $specialIsPay = 0;//免费
        }
        if ($isPay === false && $special['pay_type'] == 0 && $special['is_pink'] == 0) {//没有购买，
            $specialIsPay = 0;//免费
        }
        if ($isMember['level'] > 0 && $special['member_pay_type'] == 0) {//会员，
            $specialIsPay = 0;//免费
        }
        if ($isPay) {//购买过，
            $specialIsPay = 0;//免费
        }
        return $specialIsPay;
    }
        /**
     * 获取某个专题的任务视频列表
     * @return json
     * */
    public function get_course_list()
    {
        list($page, $limit, $special_id) = UtilService::getMore([
            ['page', 1],
            ['limit', 10],
            ['special_id', 0],
        ], null, true);
        $uid=$this->uid ? $this->uid : 0;
        $task_list = SpecialCourse::getSpecialSourceList($special_id, $limit, $page,$uid);
        if(!$task_list['list'])  return JsonService::successful([]);
        foreach ($task_list['list'] as $k => $v) {
            $task_list['list'][$k]['type_name'] = SPECIAL_TYPE[$v['type']];
            $task_list['list'][$k]['taskTrue']=SpecialWatch::whetherWatch($this->uid,$special_id,$v['id']);
        }
        return JsonService::successful($task_list);
    }
        /**
     * 播放数量增加
     * @param int $task_id 任务id
     * @return json
     * */
    public function play_num($task_id = 0)
    {
        $special_id = $this->request->param('special_id',0);
        if ($task_id == 0 || $special_id == 0) return JsonService::fail('缺少参数');
        try{
            $add_task_play_count = SpecialTask::bcInc($task_id, 'play_count', 1);
            if ($add_task_play_count) {
                $special_source = SpecialSource::getSpecialSource((int)$special_id, [$task_id]);
                if ($special_source) {
                    SpecialSource::where(['special_id' => $special_id, 'source_id' => $task_id])->setInc('play_count',1);
                }
                return JsonService::successful();
            }else {
                return JsonService::fail();
            }
        }catch (\Exception $e) {
            return JsonService::fail();
        }

    }

        /**
     * 播放任务
     * @param int $task_id 任务id
     * @return string
     * */
    public function play($task_id = 0)
    {
        if (!$task_id) $this->failed('无法访问');
        Session::set('video_token_' . $task_id, md5(time() . $task_id));
        $tash = SpecialTask::get($task_id);
        if (!$tash) $this->failed('您查看的资源不存在');
        if ($tash->is_show == 0) $this->failed('您查看的资源已下架');
        $this->assign('link', Trust($tash->link));
        $this->assign('task_id', $task_id);
        return $this->fetch();
    }
}